#include <func.h>

char* simplifyPath(char* path){
    unsigned int len = strlen(path);
    char *ret = (char *)malloc(sizeof(char) * (len + 1));
    memset(ret, 0, sizeof(char) * (len + 1));
    int top = 0;
    ret[top++] = '/';
    for(int i=0; i<len; i++){
        if(path[i] == '/' && ret[top - 1] == '/'){
            continue;
        }
        if(path[i] == '.'){
            int cnt = 0;
            while(path[i] == '.'){
                cnt++;
                i++;
            }
            i--;
            if(cnt > 2){
                for(int j=0; j<cnt; j++){
                    ret[top++] = '.';
                }
            }else if(cnt == 2){
                if((i+1 < len && path[i+1] != '/') || (i > 1 &&path[i-2] != '/')){
                    ret[top++] = '.';
                    ret[top++] = '.';
                }else if(top > 1){
                    top--;
                    while(ret[top -1] != '/'){
                        top--;
                    }
                }
            }else if((cnt == 1 && i+1 < len && path[i+1] != '/')|| path[i-1] != '/'){
                ret[top++] = '.';
            }
            continue;
        }
        ret[top++] = path[i];
    }
    while(ret[top - 1] == '/' && top > 1){
        top--;
    }
    ret[top] = '\0';
    return ret;
}

int myPwd(char* dirPath, char* pwdPath){
    strcpy(pwdPath,simplifyPath(dirPath));
    printf("%s\n",pwdPath);
}

int main(){
    char dirPath[]="/dir1/dir3/../dir2";
    char pwdPath[512];
    myPwd(dirPath,pwdPath);
    printf("%s\n",pwdPath);
    return 0;
}
